﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Money.Interfaces;
using Money.Data;
using One.Framework;

namespace Money.Services
{
    public class ClassService : IClassService
    {

        Money.Data.MoneyManagerDataContext context = new MoneyManagerDataContext();

        public ClassService()
        {
            context = new MoneyManagerDataContext();
        }

        public List<Class> GetClasses()
        {
            return context.Classes.ToList<Class>();
        }

        public Class GetClassById(int id)
        {
            return context.Classes.SingleOrDefault<Class>(ac => ac.Id == id);
        }

        public void CreateClass(Class item)
        {
            try
            {
                context.Classes.InsertOnSubmit(item);
                context.SubmitChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot create Class");
            }
        }

        public void DeleteClass(int id)
        {
            try
            {
                Class item = GetClassById(id);
                context.Classes.DeleteOnSubmit(item);
                context.SubmitChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot delete Class");
            }
        }

        public void UpdateClass(Class item)
        {
            try
            {
                context.SubmitChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot update Class");
            }
        }

        public List<Class> GetClasss(string orderBy, string orderDirection, int page, int pageSize, out int totalRecords)
        {
            try
            {
                var query = from c in context.Classes
                            select c;
                return query.OrderByPaging<Class>(orderBy, orderDirection, page, pageSize, out totalRecords).ToList<Class>();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot get classes");
            }
        }

        public bool CanDelete(int id)
        {
            Class item = GetClassById(id);
            if (item != null)
            {
                if (item.MemorizedTransactions.Count > 0 || item.Transactions.Count > 0)
                    return false;
            }
            return true;
        }
    }
}
